﻿using System;
using System.Web;
using System.Web.Mvc;
using OperationPlugins.Applications;
using OperationPlugins.Applications.Models;

namespace OperationPlugins.WebApp.Filters
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    internal sealed class ApiAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            HttpRequestHeaders headers = HttpRequestHeaders.Bind(httpContext.Request.Headers);

            if (string.IsNullOrEmpty(headers.AppId) == false)
            {
                AppInstance app;
                try
                {
                    app = ApplicationManager.GetAppInstaceByAppId(headers.AppId);
                }
                catch (Exception ex)
                {
                    // TODO: Log exception, low priority                    
                    return false;
                }

                try
                {
                    return Account.IsAuthorized(headers.Username, headers.Password, app);
                }
                catch (Exception ex)
                {
                    // TODO: Log exception, low priority
                    return false;
                }
            }

            return false;
        }
    }
}